/** 
 * @description 针对文件的操作，读取，上传
 */
Rsd.define('Rsd.data.File', {
    extend:'Rsd.common.Object',
    xtype:'ajax-file',
    type: 'POST',
    cache: false,
    /**
     * 文件元数据
     */
    metaInfo:{},
    /**
     * 支持的文件类型
     */
    types:[],
    /**
     * 文件大小自定义限制，大于该值文件不处理
     */
     maxSize : 1024 * 1024 * 10, // 限制大小10MB
    /**
     * 上传进度发生改变
     */
     progressChanged:null,
    /*
     * */
    constructor: function File(config) {
       Rsd.apply(this,config||{});
    }, 
    
    /**
     * 将file转成dataUrl ，在callback中返回
     * @param {*} file File对象
     */
    readFile: function readFile(file,callback) {
 
        //console.log(file);

        var me = this;
        // 文件类型检查
        if (me.types && me.types.length > 0 && me.types.indexOf(file.type.split("/")[1]) < 0) {
            throw new Error('不支持该文件类型'+file.type);
        }

        // 文件大小限制
        if (file.size > me.maxSize) {
            
            throw new Error('文件大小超过最大限制：'+me.maxSize/1024/1024 + 'MB');
        }
   
        // 存储文件相关信息
        this.metaInfo.type = file.type || 'image/jpeg';
        this.metaInfo.size = file.size;
        this.metaInfo.name = file.name;
        this.metaInfo.lastModifiedDate = file.lastModifiedDate;
 
        var reader = new FileReader();

        // file转dataUrl是个异步函数，要将代码写在回调里
        reader.onload = function (e) {
 
            callback(e.target.result);
             
        };
        //读取文件
        reader.readAsDataURL(file);
    },
    
    /**
     * 将dataUrl转化为 文件对象
     * @param {*} dataURL 
     */
    getFile: function getFile(dataURL) {

        var me = this;
        var binaryString = window.atob(dataURL.split(',')[1]);
        var arrayBuffer = new ArrayBuffer(binaryString.length);
        var intArray = new Uint8Array(arrayBuffer);

        for (var i = 0; i < binaryString.length; i++) 
        {
            intArray[i] = binaryString.charCodeAt(i);
        }

        var data = [intArray];

        var blob;

        try 
        {
            blob = new Blob(data, { type: me.metaInfo.type });
        } 
        catch (error)
        {
            window.BlobBuilder = window.BlobBuilder ||
                window.WebKitBlobBuilder ||
                window.MozBlobBuilder ||
                window.MSBlobBuilder;

            if (error.name === 'TypeError' && window.BlobBuilder) {
                var builder = new BlobBuilder();
                builder.append(arrayBuffer);
                blob = builder.getBlob(me.metaInfo.type);
            } 
            else 
            {
                throw new Error('版本过低，不支持上传图片');
            }
        }

         
        return new File([blob], me.metaInfo.name);

        
    },
    /**
     * 
     * @param {*} file 
     * @param {*} callback 
     */
    getDataURL:function getDataURL(file, callback){
        var a = new FileReader();
        a.readAsDataURL(file);
        a.onload = function (e){
            callback(e.target.result);
        };
    },
    /**
     * 
     * @param {*} serviceName 
     * @param {*} data | post包含文件的数据
     * @param {*} callback 
     */
    upload:function upload(serviceName,data,callback,msg)
    {
        var me = this;
        var service = Rsd.app.getService(serviceName);
 
        //application/x-www-form-urlencoded => 未找到上传文件 
        //application/form-data             => Incorrect Content-Type: application/form-data 
        //text/plain                        => Incorrect Content-Type: text/plain  
        //multipart/form-data               => Missing Content-Type Broundary=XXXX 
        //false(== text/plain)              => 415
        service.server.contentType = "multipart/form-data";// 该设置,让Rsd.data.Ajax对象会将data转化为FormData对象后再提交
        service.server.accept = "application/json, text/javascript, */*; q=0.01";
        //注册事件
        service.on('uploadloadstart',this.uploadStart);
        service.on('uploadloadend',this.uploadEnd);
        service.on('uploadprogress',this.uploadProgress); 
        service.on('uploadload',this.uploadComplete);
        service.on('uploaderror',this.uploadFailed);
        service.on('uploadabort',this.uploadAbort);
 
        //console.log(data);
        service.request(data, function (resp) {
            //console.log(resp);
            me.funApplyByIOC(callback,[resp]);
        },msg===null?'正在上传':msg); 

        return me;
    },
    /**
     * 
     * @param {*} evt 
     */
    uploadProgress:function uploadProgress(evt)
    {
        var me = this;
        if(evt.lengthComputable) 
        { 
            if(me.progressChanged)
            {
                me.funApplyByIOC(me.progressChanged,[evt]); 
                return;
            }
             
            var progress = Math.round(evt.loaded * 100 / evt.total); 

            console.debug("上传进度：" + progress);
        }
    },
    /**
     * 
     * @param {*} evt 
     */
    uploadStart:function uploadStart(evt)
    {
        console.debug ("开始上传!"); 
    },
    /**
     * 
     * @param {*} evt 
     */
    uploadEnd:function uploadEnd(evt)
    {
        console.debug ("上传结束!");  
    },
    /**
     * 
     * @param {*} evt 
     */
    uploadComplete : function uploadComplete (evt) 
    {

        if(evt.loaded == 0) 
        { 
            console.debug ("上传失败!"); 
        } 
        else 
        { 
            console.debug ("上传完成!");  
        }
        //var response = JSON.parse(evt.target.responseText); 
        console.debug ("上传完成==>",evt.target); 
    },
    /***
     * 
     */
    uploadFailed : function uploadFailed(evt) 
    { 
        console.debug ("上传出错"); 
    },
    /***
     * 
     */
    uploadAbort : function uploadAbort(evt) 
    { 
        console.debug( "上传中止!"); 
    }

},function (type) {

});
